<template>
  <div>
    <ZgDrawer width="50%" ref="formulaSet">
      <ZgPage
        ref="page"
        title="公式管理"
        addBtnName="新增公式"
        :extraHeight="220"
        :pageOpt="{showBatchBtn:false}"
        :addOpt="{title:'新增公式',width:'40%'}"
        :updateOpt="{title:'新增公式',width:'40%'}"
        @search="onSearch"
        @del="onDel"
        @add="onAdd"
        @update="onUpdate">
        <template slot="columns">
          <a-table-column title="公式名称" dataIndex="name"></a-table-column>
          <a-table-column :width="120" title="公式类型" dataIndex="cata"></a-table-column>
          <a-table-column :width="140" title="公式触发机制" dataIndex="triggerMode"></a-table-column>
        </template>
        <template slot="add">
          <Add ref="add" :formId="formId"></Add>
        </template>
        <template slot="update" slot-scope="scope">
          <Update ref="update" :jsonStr="scope.jsonStr"></Update>
        </template>
      </ZgPage>
    </ZgDrawer>
    <div @click="toFormulaSet" class="primary cpt"><slot>{{ count }}</slot>个公式</div>
  </div>
</template>
<script>
import Add from './Add'
import Update from './Update'
export default {
  components: {
    Add, Update
  },
  props: {
    formId: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      count: 0
    }
  },
  watch: {
    formId () {
      this.searchCount()
    }
  },
  mounted () {
    this.searchCount()
  },
  methods: {
    searchCount () {
      this.$http.get('/zg-autoform/formula/count', { formId: this.formId }, data => {
        this.count = data
      })
    },
    toFormulaSet () {
      this.$refs.formulaSet.open()
    },
    onSearch (param) {
      this.$http.get('/zg-autoform/formula/page', Object.assign({
        formId: this.formId
      }, param), data => {
        this.$refs.page.endSearch(
          {
            total: parseInt(data.total),
            list: data.records.map(t => {
              t.key = t.id
              return t
            })
          }
        )
      })
    },
    onDel (ids) {
      this.$http.post('/zg-autoform/formula/del', ids, () => {
        this.$refs.page.search()
      })
    },
    onAdd () {
      const result = this.$refs.add.save()
      if (!result.isOk) {
        this.$error({ title: result.msg })
        return
      }
      this.$http.post('/zg-autoform/formula/add', result.data, () => {
        this.$refs.page.hideAdd()
        this.$refs.page.search()
      })
    },
    onUpdate () {
      const result = this.$refs.update.save()
      if (!result.isOk) {
        this.$error({ title: result.msg })
        return
      }
      this.$http.post('/zg-autoform/formula/update', result.data, () => {
        this.$refs.page.hideUpdate()
        this.$refs.page.search()
      })
    }

  }
}
</script>

<style lang="scss" scoped>
</style>
